<script setup>
  import { onLoad } from '@dcloudio/uni-app'
  import { getMessageList, ReadAll, MarkRead } from '@/apis/message'
  import { ref, onMounted } from 'vue'
  import { toast } from '@/utils/utils'

  const list = ref([]) // 列表数据
  const pages = ref(0) // 总页码
  const page = ref(1) // 控制滚动条让页码加加，来发请求

  const loadData = async () => {
    const res = await getMessageList({
      contentType: 201,
      page: page.value,
      pageSize: 5,
    })
    list.value.push(...(res.data.items || []))
    pages.value = res.data.pages
  }

  onMounted(() => {
    loadData()

    //接受子组件的id-----2
    uni.$on('__message_content_get_detail', async (id) => {
      console.log(id, 'id')
      //根据id找出数组中的那一项
      const item = list.value.find((v) => v.id === id)
      if (item.isRead === 0) {
        await MarkRead(id)
      }
      // 改为已读
      item.isRead = 1
      //把item发送给子组件----3
      uni.$emit('__message_content_recetive_detail', item)
    })
  })

  //滚动条加载数据
  const onScrollToLower = () => {
    if (page.value >= pages.value) return toast('没有更多了')
    page.value++
    loadData()
  }

  //下拉刷新
  const refreshing = ref(false)
  const onRefresh = async () => {
    refreshing.value = true
    // 刷新：重新加载第一页的数据，将现有的数据清空
    page.value = 1
    list.value = []
    try {
      await loadData()
    } finally {
      refreshing.value = false
    }
  }

  //全部已读
  const ReadAlls = async () => {
    await ReadAll(201)
    console.log(list.value)
    // loadData()
    //不调接口重新渲染，直接把页面的渲染数据改了
    list.value.forEach((v) => (v.isRead = 1))
    // for (let v of list.value) {
    //   v.isRead = 1
    // }
  }
</script>

<template>
  <scroll-view
    class="scroll-view"
    :refresher-triggered="refreshing"
    refresher-enabled
    scroll-y
    @scrolltolower="onScrollToLower"
    @refresherrefresh="onRefresh"
  >
    <view class="scroll-view-wrapper">
      <view class="message-action" @click="ReadAlls">
        <text class="iconfont icon-clear"></text>
        全部已读
      </view>
      <uni-card v-for="v of list" :key="v.id" :border="false" :is-shadow="false">
        <view class="brief">{{ v.content }}</view>
        <view class="extra">
          <text class="time">{{ v.created }}</text>
          <navigator
            hover-class="none"
            class="link"
            :url="`/subpkg_message/content/index?id=${v.id}`"
            >查看详情</navigator
          >
        </view>
        <template v-slot:title>
          <view class="title" :class="{ unread: v.isRead === 0 }">{{ v.title }}</view>
        </template>
      </uni-card>
      <view v-if="list.length === 0" class="message-blank">暂无消息</view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
  @import './styles.scss';
</style>
